package cn.cvs.web;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysSupplierService;
import cn.cvs.util.Constants;
import cn.cvs.util.PageSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Auther: zwt
 * @Date: 2021/11/14 - 11 - 14 - 18:31
 * @Description: cn.cvs.web
 * @version: 1.0
 */
@Controller
public class SysSuppliersController {
    @Resource
    SysSupplierService sysSupplierService;

    //供应商列表
    @RequestMapping("/sys/supplier/list")
    public String list(@RequestParam(value = "querySupCode",required = false) String supCode, @RequestParam(value = "querySupName",required = false) String supName, @RequestParam(value = "pageIndex",required = false,defaultValue = "1")  Integer pageNo, Model model){
        model.addAttribute("querySupCode",supCode);
        model.addAttribute("querySupName",supName);
        //供应商列表
        List<Supplier> supplier = sysSupplierService.querySupplier(supCode, supName, pageNo, Constants.pageSize);
        model.addAttribute("supplierList",supplier);
        //totalCount 总记录数
        int count = sysSupplierService.queryCount(supCode, supName);
        model.addAttribute("totalCount",count);
        //currentPageNo 当前页码
        model.addAttribute("currentPageNo",pageNo);
        //totalPageCount 总页数
        PageSupport pageSupport = new PageSupport();
        //设置pageSize
        pageSupport.setPageSize(Constants.pageSize);
        //设置参与分页的总记录数
        pageSupport.setTotalCount(count);
        //获得总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "supplier/list";
    }

    //跳转到添加供应商页面
    @RequestMapping("/sys/supplier/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

//    @PostMapping("/sys/supplier/add")
//    public String add(Supplier supplier, HttpSession session, Model model){
//        System.out.println("-----------------------------------------------------------------------------------");
//        //验证用户是否登录
//        SysUser login = (SysUser)session.getAttribute(Constants.USER_SESSION);
//        System.out.println(supplier);
//        if (login==null) {
//            model.addAttribute("error","请登录后操作！");
//            return "forward:toLogin";
//        }
//
//        //设置创建时间
//        supplier.setCreatedTime(new Date());
//        //设置创建者id
//        supplier.setCreatedUserId(login.getId());
//        int i = sysSupplierService.addSupplier(supplier);
//        if (i>0) {
//            //添加供应商成功
//            //重定向回供应商列表
//            return "redirect:/sys/supplier/list";
//        }else{
//            //添加用户失败
//            throw new RuntimeException("添加供应商失败，请稍后再试！");
//        }
//    }
@PostMapping("/sys/supplier/add")
public String add(Supplier supplier, BindingResult bindingResult, HttpSession session, HttpServletRequest request, Model model, @RequestParam(value = "attachs",required = false) MultipartFile[] attachs){
    //验证用户是否登录
    SysUser login = (SysUser)session.getAttribute(Constants.USER_SESSION);
    System.out.println(supplier);
    if (login==null) {
        model.addAttribute("error","请登录后操作！");
        return "forward:toLogin";
    }
    //查看后台验证的结果
    if(bindingResult.hasErrors()){
        //后台验证错误
        throw new RuntimeException("后台数据校验错误！");
    }
    for (int i = 0; i < attachs.length; i++) {
        String saveFileName = System.currentTimeMillis() + "_" + attachs[i].getOriginalFilename();
        String realPath = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File saveFile = new File(file,saveFileName);
        try {
            attachs[i].transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("保存图片失败",e);
        }
        String path=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
        if(!attachs[i].isEmpty()){
            if(i==0){
                supplier.setCompanyLicPic(path);
            }else{
                supplier.setOrgCodePic(path);
            }
        }
    }


    //设置创建时间
    supplier.setCreatedTime(new Date());
    //设置创建者id
    supplier.setCreatedUserId(login.getId());
    int i = sysSupplierService.addSupplier(supplier);
    if (i>0) {
        //添加供应商成功
        //重定向回供应商列表
        return "redirect:/sys/supplier/list";
    }else{
        //添加用户失败
        throw new RuntimeException("添加供应商失败，请稍后再试！");
    }
}

    //跳转到修改页面
    @RequestMapping("/sys/supplier/toUpdate/{supId}")
    public String toUpdate(@PathVariable("supId") Integer id, Model model){
        Supplier supplier = sysSupplierService.queryById(id);
        model.addAttribute("supplier",supplier);
        return "/supplier/update";
    }

    //修改供应商
    @PostMapping("/supplier/update")
    public String updateSupplier(Supplier supplier, HttpSession session, Model model){
        //登陆验证
        SysUser login = (SysUser)session.getAttribute(Constants.USER_SESSION);
        if(login==null){
            //还没有登陆
            model.addAttribute("error", "请登录后操作！");
            return "forward:/toLogin";
        }
        //修改时间
        supplier.setUpdatedTime(new Date());
        //修改供应商id
        supplier.setUpdatedUserId(login.getId());
        int i = sysSupplierService.updateSupplier(supplier);
        if(i>0){
            //修改成功
            //重定向到供应商列表
            return "redirect:/sys/supplier/list";
        }else{
            throw new RuntimeException("修改失败，请稍后再试!");
        }
    }

    //查看详情
    @GetMapping("/sys/supplier/view/{supId}")
    public String viewSuppliers(@PathVariable("supId") Integer id, Model model){
        Supplier supplier = sysSupplierService.queryById(id);
        model.addAttribute("supplier",supplier);
        return "/supplier/view";
    }

    //删除


}
